import {Component} from 'react'
import axios from "axios";
import {Button, Checkbox, Divider, message} from 'antd';
import './SetLimit.css'
const CheckboxGroup = Checkbox.Group;
const plainOptions = ['Apple', 'Pear', 'Orange'];
const defaultCheckedList = ['Apple', 'Orange'];
const id = 0;
let idArr= [];
class SetLimit extends Component{
    constructor(props) {
        super(props);
        this.state = {
            limits:[],     //权限列表模板
            checkoutIdList:[],  //用户选择的权限列表
            limitsList:[],
            parentId:''
        };
        this.roleId = '';
    }
    componentWillMount() {
        if(this.props.history){   //从编辑跳到该页面
            this.roleId = this.props.history.location.state.roleId;
            console.log('in');
            axios.get('/api/admin/admin/updateAuthPage',{
                params:{
                    roleId:Number(this.roleId)
                },
                headers:{
                    'Content-Type':'application/x-www-form-urlencoded'
                }
            }).then((res)=>{
                console.log('in',res)
                if(res.status==200){
                    this.setState({
                        limitsList:[...res.data.data.menu]
                    },()=>{
                        //初始化，取消所有选中，并生成checkout模板
                        this.setState({
                            limits:this.SetComponent(this.state.limitsList)
                        })
                    });

                }
            })
        }else {     //从添加按钮跳到该页面
            //获取所有的编辑权限列表
            axios.get('/api/admin/admin/updateAuthPage',{
                params:{
                    roleId:'21'
                },
                headers:{
                    'Content-Type':'application/x-www-form-urlencoded'
                }
            }).then((res)=>{
                this.setState({
                    limitsList:[...res.data.data.menu]
                });
                //初始化，取消所有选中，并生成checkout模板
                this.setState({
                    limits:this.SetComponent(this.cancelAllLimits(this.state.limitsList,0))
                })

            });
        }
    }
    //向父级发送所有id
    sendAllId(){
        idArr = [];
        let sendData = this.getAllId(this.state.limitsList);
        return sendData
    }
    //获取选中的所有menuId
    getAllId(list){
        list.forEach(item=>{
            if(item.childrens && item.childrens.length>0){
                if(item.isAuth==1){
                    idArr.push(item.menuId);
                    // console.log('arr',idArr);
                }
                this.getAllId(item.childrens)
            }else {
                if(item.isAuth==1){
                    idArr.push(item.menuId);
                    // console.log('arr',idArr)
                }
            }
        });
        return idArr
    }
    //checkbox的change事件
    checkoutChange=(e)=>{
        var menuId = e.target.data;    //获取当前选中的菜单id
        if(e.target.checked == true){
            this.setState({
                limitsList:this.getChildren(this.state.limitsList,menuId,1)
            },()=>{
                console.log(this.state.limitsList);
                this.setState({
                    limits:this.SetComponent(this.state.limitsList)
                })
            });      //获取当前选中权限及其所有子级
        }else {
            this.setState({
                limitsList:this.getChildren(this.state.limitsList,menuId,0)
            },()=>{
                console.log(this.state.limitsList)
                this.setState({
                    limits:this.SetComponent(this.state.limitsList)
                })
            });
        }


    };
    //获取当前选中权限及其所有子级
    getChildren(list,menuId,num){
        list.forEach(item=>{
            if(item.menuId == menuId){
                if(item.childrens && item.childrens.length>0){
                    item.isAuth = num;
                    this.cancelAllLimits(item.childrens,num)
                }else {
                    item.isAuth = num;
                }
            }else {
                if(item.childrens && item.childrens.length>0){
                    this.getChildren(item.childrens,menuId,num)
                }
            }
        });
        return list;
    };
    //生成模板
    SetComponent(list){
        var arr = [];
        list.forEach(item=>{
            if(item.childrens && item.childrens.length>0){     //有子级
                arr.push(
                    <div key={item.menuId} className={'groupCheck groupCheck'+item.menuLevel}>
                        <Checkbox
                            key={item.menuId}
                            defaultChecked={item.isAuth}
                            className='itemCheck'
                            checked={item.isAuth}
                            data={item.menuId}
                            onChange={(e)=>{this.checkoutChange(e)}}>
                            {item.menuName}
                        </Checkbox>
                        {this.SetComponent(item.childrens)}
                    </div>);

            }else {   //无子级
                    arr.push(
                        <div key={item.menuId} className={'groupCheck'+item.menuLevel}>
                        <Checkbox
                            key={item.menuId}
                            checked={item.isAuth}
                            defaultChecked={item.isAuth}
                            className='itemCheck'
                            data={item.menuId}
                            onChange={(e)=>{this.checkoutChange(e)}}>
                            {item.menuName}
                        </Checkbox>
                        </div>);
            }
        });
        return arr;
    }
    //改变选中状态
    cancelAllLimits(list,num){
        list.forEach(item=>{
            if(item.childrens && item.childrens.length>0){
                item.isAuth = num;
                this.cancelAllLimits(item.childrens,num)
            }else {
                item.isAuth = num;   //将所有的选中权限取消,0:无该权限，1：有该权限
            }
        });
        return list;
    };
    submit=()=>{
        var arr = this.sendAllId();
        axios.get("/api/admin/admin/updateAuthDo", {
            params: {
                roleId: this.roleId.toString(),
                ids: arr.join(),
            },
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            }
        }).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
                message.success('编辑成功');
                this.props.history.push('/accountManage');
            }else {
                message.err(res.data.msg);
            }
        });
    };
    render() {
        return (
            <>
                {this.state.limits}
                {this.roleId?<Button className='bt_edit' type="primary" onClick={this.submit}>
                                {/*<Link to='/accountManage'>提交</Link>*/}
                                提交
                             </Button>:''}
            </>
        );
    }
}

export default SetLimit
